import { defineStore } from 'pinia'
import { login, register, logout } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('crm-token') || null,
    user: JSON.parse(localStorage.getItem('crm-user') || 'null')
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    userRole: (state) => state.user?.role || '普通员工'
  },
  
  actions: {
    async login(credentials) {
      const res = await login(credentials)
      this.token = res.token
      this.user = res.user
      localStorage.setItem('crm-token', res.token)
      localStorage.setItem('crm-user', JSON.stringify(res.user))
      return res
    },
    
    async register(data) {
      return await register(data)
    },
    
    async logout() {
      await logout()
      this.token = null
      this.user = null
      localStorage.removeItem('crm-token')
      localStorage.removeItem('crm-user')
    }
  }
})